package com.haojiangbo.mysql;



import com.haojiangbo.model.ConfigModel;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/***
 * 执行sql语句
 */
public class SqlFunction {

    public List<ConfigModel> findAll() {
        List<ConfigModel> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        //抓取异常
        try {
            //注册驱动
            Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println(aClass);
            //获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://124.223.14.84:3306/test?serverTimezone=GMT%2B8&useSSL=false", "root", "123456");
            //获取操作数据库的对象
            pst = connection.prepareStatement("select * from config ");
            //获取数据
            rs = pst.executeQuery();
            //通过while循环遍历输出全部数据，然后封装成为Items对象，添加到集合list对象
            while (rs.next()) {
                ConfigModel configModel = new ConfigModel();
                configModel.setDomain(rs.getString("domain"));
                configModel.setClientId(rs.getString("clientId"));
                configModel.setClientUrl(rs.getString("clientUrl"));
                configModel.setPort(rs.getInt("port"));
                configModel.setRate(rs.getInt("rate"));
                list.add(configModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源，但是需要对象存在的情况下才能释放，
            //所以必须在在try...catch..外先创建其对象先，定义为null，确保不会报错
            if(rs != null ) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(pst != null ) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null ) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return list;
    }


}
